I am trying to apply data by adding _copy to the name and of course a new ID but I am not at all expert cakePHP and I do not know where to start. Here is my view:
I add the button "duplicate" with a route in the controller
<td>
<?php echo $this->Html->link(
'Dupliquer',
array(
'controller' => 'contracts',
'action' => 'duplicate',
$contract['Contract']['id']
),
array(
'class' => 'btn btn-default btn-sm'
)
); ?>
</td>
The function I call in my controller:
public function duplicate($id = null) {
if (!$id)
{
throw new NotFoundException(__('Identifiant invalide'));
}
$contract = $this->Contract->find('first', [
'conditions' => [
'Contract.id' => $id
]
]);
if (!$this->Contract->HasAny(['Contract.id' => $id])) {
throw new NotFoundException(__('Le contrat n\'a pas pu être trouvé'));
}
$data = [
'name' => $contract['Contract']['name']. '_copy',
];
return $this->redirect('edit');
}
In my function I retrieve the information to duplicate and it is here that I stuck at the level of the recording. Do you have an idea how to do it to make it clean?
Thank you.
Change:
$contract = $this->Contract->findById($id);
to:
$contract = $this->Contract->find()->where(['id' => $id])->first();
then:
$data = [
'name' => $contract->name. '_copy',
// other fields ...
];
$entity = $this->Contracts->newEntity($data);
$this->Contracts->save($entity);
// ...
// $this->redirect($this->referer());
Related
Goodnight (or good morning),
I trying to upload multiple files at the same time. I am following the cookbook instructions to build the solution. I always got first file (not and array of files).
Here is my view code...
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Upload $upload
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Uploads'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="uploads form content">
<?= $this->Form->create($upload, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Upload') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('document_type_id', ['options' => $documentTypes]);
echo $this->Form->control('period_id', ['options' => $periods]);
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('documents', ['type' => 'file', 'label' => __('Choose PDF Files'), 'accept' => 'application/pdf', 'multiple' => 'multiple']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
And here is my controller code...
public function add()
{
$upload = $this->Uploads->newEmptyEntity();
if ($this->request->is('post')) {
$upload = $this->Uploads->patchEntity($upload, $this->request->getData());
if ($this->Uploads->save($upload)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$documents = $this->request->getData('documents');
$this->loadModel('Dockets');
$dockets = $this->Dockets->findByDocketStateId(1);
$documents_ok = 0;
$documents_nok = 0;
$dockets_without_document = 0;
foreach($documents as $documents_key => $document_to_save)
{
foreach($dockets as $dockets_key => $docket)
{
$contents = file_get_contents($document_to_save);
$pattern = str_replace('-', '', $pattern);
$pattern = str_replace('', '', $pattern);
$pattern = preg_quote($docket->cuit, '/');
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$documentsTable = $this->getTableLocator()->get('Documents');
$document = $documentsTable->newEmptyEntity();
$document->upload_id = $upload->id;
$document->document_type_id = $upload->document_type_id;
$document->period_id = $upload->period_id;
$document->docket_id = $docket->id;
$document->user_id = $this->getRequest()->getAttribute('identity')['id'];
if ($documentsTable->save($document)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$fileobject = $this->request->getData('document');
$destination = $this->Parameters->findByName('document_directory')->first()->toArray()['value'] . 'document_' . $document->id . '.pdf';
// Existing files with the same name will be replaced.
$fileobject->moveTo($destination);
}
$this->Flash->error(__('The document could not be saved. Please, try again.'));
$documents_ok = $documents_ok + 1;
unset($dockets[$dockets_key]);
unset($documents[$documents_key]);
break;
}
}
}
if(!empty($documents)){
//print_r($documents);
$documents_nok = count($documents);
unset($documents);
}
if(!empty($dockets)){
$dockets_without_document = count($dockets);
unset($dockets);
}
$message = __('There were processed ') . $documents_ok . __(' documents succesfully. ') . $documents_nok . __(' documents did not math with a docket. And ') . $dockets_without_document . __(' active dockets ddid not not have a document.');
$this->Flash->success(__('The upload has been saved. ') . $message);
return $this->redirect(['action' => 'view', $upload->id]);
}
$this->Flash->error(__('The upload could not be saved. Please, try again.'));
}
$documentTypes = $this->Uploads->DocumentTypes->find('list', ['keyField' => 'id',
'valueField' => 'document_type',
'limit' => 200]);
$periods = $this->Uploads->Periods->find('list', ['keyField' => 'id',
'valueField' => 'period',
'limit' => 200]);
$users = $this->Uploads->Users->find('list', ['keyField' => 'id',
'valueField' => 'full_name',
'conditions' => ['id' => $this->getRequest()->getAttribute('identity')['id']],
'limit' => 200]);
$this->set(compact('upload', 'documentTypes', 'periods', 'users'));
}
Can you help me to understand what I doing wrong?
Thanks,
Gonzalo
When using PHP, multi-file form inputs must have a name with [] appended, otherwise PHP isn't able to parse out multiple entries, they will all have the same name, and PHP will simply use the last occurrence of that name.
echo $this->Form->control('documents', [
'type' => 'file',
'label' => __('Choose PDF Files'),
'accept' => 'application/pdf',
'multiple' => 'multiple',
'name' => 'documents[]',
]);
Furthermore the following line:
$fileobject = $this->request->getData('document');
should probably be more like this, as there a) is no document field and b) even if there were, you most likely wouldn't want to process the same file over and over again:
$fileobject = $documents[$documents_key];
Also make sure that you have proper validation in place for the uploaded files, even if you don't seem to use the user provided file information, you should still make sure that you've received valid data!
How to edit a record with Cakephp and modal bootstrap?
Because when I edit a contact, I get the error 500?
missing view The view for UserContactsController:: admin_modal_edit()
was not found.
In to controller admin_modal_edit() I have set $this->layout = NULL;
These are the files of the app.
File: user/view.ctp with list of contact and the modal for add or edit.
BUTTON FOR EDIT OR DELETE
<?php echo $userContact['UserContactType']['title']; ?>: <?php echo $userContact['contact']; ?>
<?php echo __('Edit'); ?>
BOOTSTRAP MODAL
<?php
echo $this->Form->create('UserContact', array('url' => array('admin' => true, 'prefix' => 'admin', 'plugin' => 'user', 'controller' => 'user_contacts', 'action' => 'modal_edit')));
?>
<?php echo $this->Form->input('UserContact.id', array('class' => 'form-control')); ?>
<?php echo $this->Form->input('UserContact.user_id', array('default' => $user_id, 'type' => 'hidden')); ?>
<?php echo $this->Form->input('UserContact.user_contact_type_id', array('class' => 'form-control', 'empty' => true)); ?>
<?php echo $this->Form->input('UserContact.contact', array('class' => 'form-control')); ?>
<?php echo $this->Form->submit(__('Save'), array('div' => false, 'class' => 'btn btn-success')); ?>
<?php echo $this->Form->end(); ?>
File: controller/UsersController.php that generates view.ctp
public function admin_view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$user_id = $id;
$options = array(
'contain' => array('UserContact' => 'UserContactType', 'UserGroup', 'UserState', 'UserGender', 'UserAddress' => 'UserAddressType', 'UserPaymentType', 'Item', 'Comment'),
'conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
// blocco find list
$userContactTypes = $this->UserContactType->find('list');
$userAddressTypes = $this->UserAddressType->find('list');
$this->set(compact(array('userContactTypes', 'userAddressTypes', 'user_id')));
}
File: controller/UserContactsController.php for the modal
public function admin_modal_edit() {
$id = $this->request->query('id');
$this->layout = NULL;
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}
Your issue is that CakePHP is trying to render the 'admin_modal_edit.ctp' View template.
If you don't want CakePHP to render anything set autoRender to false:-
public function admin_modal_edit() {
$this->autoRender = false;
}
This will prevent CakePHP from looking for a View template to render.
$this->layout = null does not stop Cake from attempting to render templates. Which I suspect is what you're trying to achieve.
This error is showing because cakephp is complaining about the function admin_modal_edit for not having a view since it cannot find the admin_modal_edit.ctp in the view folder of your controller.
To fix this, add this
$this->autoRender = false
to your function admin_modal_edit to disable the rendering of view for that function.
So your function should look like this.
public function admin_modal_edit() {
/** -------------- **/
$this->autoRender = false;
/** -------------- **/
$id = $this->request->query('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}
I am new in CakePHP. I wanted to create menu in cakePHP 2.3.9 but when I run the application it gives following warning "rawurlencode() expects parameter 1 to be string, array given [CORE\Cake\Routing\Route\CakeRoute.php, line 506]"
I am giving the complete code here. I can not understand how to eliminate the warning message above.
At first I have created this file at /app/Model/menu.php. Which looks like this
<?php
class Menu extends AppModel {
var $name = 'Menu';
var $useTable = false;
function main ($selected = 'home') {
return array(
'divClass' => 'menu',
'ulClass' => 'menu',
'tabs' => array(
array(
'controller' => 'pages',
'action' => '',
'params' => '',
'aClass' => $selected == 'home' ? 'selected' : '',
'liClass' => '',
'text' => 'Home'
),
array(
'controller' => 'pages/service',
'action' => '',
'params' => '',
'aClass' => $selected == 'Service' ? 'selected' : '',
'liClass' => '',
'text' => 'Service'
),
array(
'controller' => 'pages/user',
'action' => '',
'params' => '',
'aClass' => $selected == 'users' ? 'selected' : '',
'liClass' => '',
'text' => 'Users'
),
)
); // end return
} // end Main
} // end class Menu
?>
Then I have created this file at /app/Controller/MenusController.php. Which looks like this
<?php
class MenusController extends AppController {
var $name = 'Menus';
private $menus;
function beforeFilter () {
parent::beforeFilter();
$this->menus[] = array(
'name' => 'main',
'selected' => 'users'
);
// $this->set('menuList', $this->menus);
}
function index() {
$this->menus[] = array(
'name' => 'users',
'selected' => 'users'
);
$this->set('menuList', $this->menus);
}
function menus($menus) {
$output = array();
foreach ($menus as $menu):
$output[] = $this->Menu->{$menu['name']}($menu['selected']);
endforeach;
return $output;
}
}
?>
Then, this file I have created at /app/View/Elements/menu.ctp, which looks like this
<?php
if (empty($menuList)):
$menuList = array(
array(
'name' => 'main',
'selected' => 'home'
)
);
endif;
$menus = $this->requestAction(
array(
'controller' => 'menus',
'action' => 'menus'
),
array('pass' => array( $menuList))
);
if (! empty($menus)):
foreach ($menus as $menu):
$tabs = '';
foreach ($menu['tabs'] as $tab):
$url = array(
'controller' => $tab['controller'],
'action' => $tab['action']
);
if (! empty($tab['params'])):
$url[] = $tab['params'];
endif;
$tabs .= $this->html->tag(
'li',
$this->html->link(
$tab['text'],
$url,
array('class' => $tab['aClass'])),
array('class' => $tab['liClass'])
);
endforeach;
echo '<div class="' . $menu['divClass'] . '">
<div class="container_12">
<div class="grid_12">' . $this->html->tag('ul', $tabs, array('class' =>
$menu['ulClass'])) . '</div></div></div>';
endforeach;
endif;
?>
accept my advance gratitude for help
Your framework might have a default helper function which uses php's rawurlencode() function by default too. You might want to check the parameters you should pass for $this->html->link() since php's rawurlencode() function accepts only a string as a parameter.
Although the documentation says requestAction now supports 'array based cake style URLs' which 'bypass the usage of Router::url()', try passing a string as the first parameter to request action.
For example where you currently have:
array(
'controller' => 'menus',
'action' => 'menus'
),
Try:
'menus/menus',
I am developing a plugin for CakePHP 2.
My problem is below:
I have a view with a filter search, where users can search by category:
<div>
<?php echo $this->Form->create('Permission'); ?>
<fieldset>
<?php echo $this->Form->input("permissionCategory", array('label' =>
__d('permission_manager','Categoría'), 'options' => $categorias, 'empty' =>
__d('permission_manager','-- Categorías --'), 'default' => '','class' => 'select-cat', 'onchange' => 'this.form.submit()')); ?>
</fieldset>
<?php //echo $this->Form->end(__d('permission_manager','Aceptar')); ?>
</div>
When I do click over delete button, it shows the confirm message, but when I push yes, the item is not deleted.
I realized it has relation with the action. Maybe with the request type.
The action code:
public function index() {
$this->paginate = array('order' => 'Permission.category asc, Permission.code asc');
$this->Permission->recursive = 2;
if($this->request->is('post')) {
if(empty($this->request->data['Permission']['permissionCategory'])) {
$conditions = null;
} else {
$cat = $this->Permission->findById($this->request->data['Permission']
['permissionCategory']);
$conditions = array('Permission.category ' => $cat['Permission']['category']);
}
$this->Paginator->settings = array(
'conditions' => $conditions );
}
$this->set('categorias', $this->Permission->find('list', array('fields' => 'category',
'group' => 'category')));
$this->set('permissions', $this->Paginator->paginate());
}
Edit:
My delete button:
(I have one like this for row in DB)
<?php echo $this->Form->postLink($this->Html->image('PermissionManager.cross.png',
array('title' =>
__d('permission_manager','Borrar'))),'delete/'.h($permission['Permission']['id']),
array( 'escape' => false), __d('permission_manager','Are you sure... ?'));
?>
My delete action:
public function delete($id = null) {
$this->Permission->id = $id;
if (!$this->Permission->exists()) {
//throw new NotFoundException(__d('permission_manager','Permiso inexistente'));
$this->Session->setFlash(__d('permission_manager','Permiso inexistente'), 'default', array('class'=>'error'));
return $this->redirect(array('action' => 'index'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Permission->delete()) {
$this->Session->setFlash(__d('permission_manager','El permiso ha sido borrado correctamente.'), 'default', array('class'=>'success'));
} else {
$this->Session->setFlash(__d('permission_manager','El permiso no ha podido borrarse. Por favor, inténtelo de nuevo.'), 'default', array('class'=>'error'));
}
return $this->redirect(array('action' => 'index'));
}
help me to fix isPut or isPost for save logic, in the following code i can view the data in the from, but when i am trying to save it its not working, i have tried ispost and isput logic both are not working. i think problem is with controller sections not with view
here is view of my form,
<?php
echo $this->Form->create('Role',array('url'=>array('controller'=>'Organisations','action' => 'edit_profile'),'id' => 'role'));
echo $this->Form->input('RoleLanguage.rolename',array('label'=>'Profile Name:','id'=>'rolename'));
$options = array('A' => 'Approve', 'P' => 'Pending', 'D' => 'Delete');
echo $this->Form->input('Role.status', array(
'options'=>$options,
'empty' => false,
'label'=>'Status',
'style'=>'width:100px',
'id'=>'status'
));
$id= array('value' => $id);
//print_r($id);die();
echo $this->Form->hidden('rle_id', $id);
echo "<br>";
$options = array('R' => 'Role', 'P' => 'Position', 'T' => 'Team','C'=>'Core Strategic Profile');
echo $this->Form->input('Role.type', array(
'options'=>$options,
'empty' => false,
'label'=>'Type of Job Profile:',
'style'=>'width:100px',
'id'=>'type'
));
echo "<br>";
echo $this->Form->input('RoleLanguage.external_document_URL',array('label'=>'External Document URL:','id'=>'external_document_URL','type'=>'text'));
echo "<br>";
echo $this->Form->input('RoleLanguage.description', array('style'=>'width:420px','rows' => '5', 'cols' => '5','label'=>'Description','id'=>'description'));
?>
here is controller logic
function edit_profile($id=NULL)
{
$this->layout='Ajax';
//print_r($id);die();
$this->set('id',$id);
$this->Role->recursive = 0;
$this->Role->id = $id;
$language = $this->getLanguage('content');
$this->Role->unBindModel(array("hasMany" => array('RoleLanguage')));
$this->Role->bindModel(array("hasOne" => array('RoleLanguage'=> array('foreignKey' => 'rle_id', 'className' => 'RoleLanguage', 'type' => 'INNER', 'conditions' => array('RoleLanguage.language' => $language)))));
$this->data = $this->Role->read();
//print_r($this->data);die();
if ($this->RequestHandler->isPut())
{
$this->data=array(null);
$this->autoRender = false;
$acc_id = $this->activeUser['User']['acc_id'];
$this->data['Role']['acc_id'] = $acc_id;
unset($this->Role->RoleLanguage->validate['rle_id']);
print_r($this->data);die();
$this->Role->saveAll($this->data);
}
}
i am serializing data in another view from where i am calling the qbove view code for that is
$.ajax({
type: 'Put',
url: $('#role').attr('action'),
data: $('#role').serialize()
It could be that the data is failing the model validation test that occurs when you call saveAll.
Have you tried printing $this->Role->invalidFields() to see if there is anything there?