cakephp check the num after delete - cakephp

I want to check the num of market if true num then delete and redirect in index else redirect error
in controller:
public function admin_verif_num() {
$this->set('title_for_layout', __('verification'));
$this->Market->recursive = 2;
$markets = $this->Market->find('list', array(
'fields' => array('Market.num_mark')
));
if (!empty($this->request->data)) {
$num= $this->request->data['Market']['num_mark'];
foreach ($markets as $nums) {
if ($nums == $num) {
$id= $this->request->id;
$this->Session->setFlash(__('good'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'delete',$id,true), null, __('Are you sure?'));
} else{
$this->Session->setFlash(__('error'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'admin_verif_delete_num'));
}
}
}
$this->set('markets', $markets);
}
in view:
<?php
echo $this->Form->label('num_mark', ' : طلب الع'); ?>
<?php echo $this->Form->input('num_mark',array('label' => false ));
?>
the result is http://localhost/bib/admin/markets/delete/1
but not delete what is the true code ?

Related

cakephp 2, edit record in modal by bootstrap

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

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.

Issue deleting items with filter search

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'));
}

CakePHP login by Username Or Email using Auth component

In my present system I need to login using username or email and password.
can anybody knows how to achieve this ?
My Form:
<?php echo $this->Form->create('User', array('action' => 'login'));
echo $this->Form->input('username', array('class' => 'TextField js-user-mode'));
echo $this->Form->input('password', array('class' => 'TextField'));
?>
MY AppController:
public $components = array(
'Email'=>array(),
'Auth' => array(
'loginAction' => array(
'admin' => false,
'controller' => 'users',
'action' => 'login'
),
'authError' => 'Your session has ended due to inactivity. Please login to continue.',
'authenticate' => array(
'Form' => array(
'fields' => array('username' => array('username','email')),
),
'all' => array(
'userModel' => 'User',
'scope' => array('User.status' =>array('active'))
)
)
)
);
Let me know what else i need to do..??
I'm not sure what the etiquette is on posting answers to old questions but here's what I did for this.
In my login function
$username = $this->data['User']['username'];
$password = $this->request->data['User']['password'];
$user = $this->User->findByUsername($username);
if (empty($user)) {
$user = $this->User->findByEmail($username);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
$this->request->data['User']['username'] = $user['User']['username'];
}
I found following code from this url. I think this is the best in sense of simplicity. Use following code on your login action:
public function login() {
if($this->request->is('post')&&!empty($this->request->data)) {
App::Import('Utility', 'Validation');
if( isset($this->data['User']['username']) && Validation::email($this->request->data['User']['username'])) {
$this->request->data['User']['email'] = $this->request->data['User']['username'];
$this->Auth->authenticate['Form'] = array('fields' => array('username' => 'email'));
}
if($this->Auth->login()) {
/* login successful */
$this->redirect($this->Auth->redirect());
} else {
/* login unsuccessful */
}
}
}
And also use following code for login.ctp :
<?php
echo $this->form->create('User');
echo $this->form->input('username');
echo $this->form->input('password');
echo $this->form->end('Submit');
?>
Simply we can do this before your Auth login action:
$emailUsername = #$this->request->data['User']['email'];
if (!filter_var($emailUsername, FILTER_VALIDATE_EMAIL)) {
$emailFromUsername = $this->User->find('first', array('conditions' => array('User.username' => $emailUsername), 'recursive' => -1, 'fields' => array('email')));
//pr($emailFromUsername );
if (!empty($emailFromUsername)) {
$emailFromUsernameDB = $emailFromUsername['User']['email'];
} else {
$emailFromUsername = '';
}
$this->request->data['User']['email'] = $emailFromUsername;
}
Assuming you have username and email both fields in your users table
In your AppController.php
public function beforeFilter() {
if ($this->request->is('post') && $this->action == 'login') {
$username = $this->request->data['User']['username'];
if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
$this->Auth->authenticate['Form']['fields']['username'] = 'email';
$this->request->data['User']['email'] = $username;
unset($this->request->data['User']['username']);
}
}
}
This code will work for CakePHP 2.x, not tested on version 3.x, you should have email field in your user's table.
You can leverage the MultipleColumn Auth adapter:
https://github.com/ceeram/Authenticate/blob/master/Controller/Component/Auth/MultiColumnAuthenticate.php
Update:
New version # https://github.com/dereuromark/cakephp-tools/blob/master/src/Auth/MultiColumnAuthenticate.php
I found this solution useful.
I have created two classes that extend FormAuthenticate:
app/Controller/Component/Auth/ClassNameAuthenticate.php and
<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class ClassNameAuthenticate extends FormAuthenticate {
}
app/Controller/Component/Auth/ClassNameEmailAuthenticate.php
<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class ClassNameEmailAuthenticate extends FormAuthenticate {
}
then in my Controller added Auth Component to $components
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'ClassName' =>array(
'userModel'=>'ClassName',
'fields' => array(
'username' => 'username',
),
'scope' => array('ClassName.active' => 1)
),
'ClassNameEmail' =>array(
'userModel'=>'ClassName',
'fields' => array(
'username' => 'email',
),
'scope' => array('ClassName.active' => 1)
)
)
),
);
login view: login.ctp
<div class="form">
<?php echo $this->Form->create('ClassName'); ?>
<fieldset>
<legend><?php echo __('Login'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(array('label'=>__('Login'))); ?>
</div>
and login() action:
public function login(){
if ($this->Auth->loggedIn()) {
return $this->redirect($this->Auth->redirect());
}
if ($this->request->is('post')) {
//Need to duplicate field email for ClassNameEmail Auth
$this->request->data['ClassName']['email'] = $this->request->data['ClassName']['username'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username/email or password, try again'));
}
}
I hope someone will find this useful.
this is my solution to solve that problem
public function login(){
if($this->request->is('post')){
$this->User->set($this->request->data);
if($this->User->validates()){
if(Validation::email($this->data['User']['username'])){
$this->Auth->authenticate['Form'] = array_merge($this->Auth->authenticate['Form'],array('fields'=>array('username'=>'email')));
$this->request->data['User']['email'] = $this->request->data['User']['username'];
unset($this->request->data['User']['username']);
}
if($this->Auth->login()){
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_login',time());
if($this->data['User']['remember']){
unset($this->request->data['User']['remember']);
$this->request->data['User']['password'] = Security::hash($this->request->data['User']['password'],'blowfish');
$this->Cookie->write('rememberMe',$this->request->data['User'],true,'2 days');
}
$this->redirect($this->Auth->loginRedirect);
}
$this->Session->setFlash('Invalid Username or Password entered, please try again.','default',array('class'=>'alert alert-warning'),'warning');
}
}
$this->set('title','Login Page');
}

form action linking to wrong controller

I have a a controller referral_medium_controller.php with the following content
<?php
class ReferralMediumsController extends AppController
{
var $name = 'ReferralMediums';
function admin_index()
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Referral Mediums');
$this->ReferralMediums->recursive = 0;
$this->set('ReferralMediums', $this->paginate());
}
function admin_view($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Referral Mediums?');
if (is_null($id)) {
$this->cakeError('error404');
}
$referralMedium = $this->ReferralMediums->find('first', array(
'conditions' => array(
'ReferralMedium.id = ' => $id
) ,
'fields' => array(
'ReferralMedium.id',
'ReferralMedium.created',
'ReferralMedium.modified',
'ReferralMedium.referral_medium',
'ReferralMedium.is_active',
) ,
'recursive' => -1,
));
if (empty($referralMedium)) {
$this->cakeError('error404');
}
$this->pageTitle.= ' - ' . $referralMedium['ReferralMedium']['id'];
$this->set('ReferralMediums', $referralMedium);
}
function admin_add()
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Add Referral Medium');
if (!empty($this->data)) {
$this->ReferralMedium->create();
if ($this->ReferralMedium->save($this->data)) {
$this->Session->setFlash(__l('Referral Medium has been added') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__l('Referral Medium could not be added. Please, try again.') , 'default', null, 'error');
}
}
}
function admin_edit($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Edit Referral Medium');
if (is_null($id)) {
$this->cakeError('error404');
}
if (!empty($this->data)) {
if ($this->ReferralMedium->save($this->data)) {
$this->Session->setFlash(__l('Referral Medium has been updated') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__l('Referral Medium could not be updated. Please, try again.') , 'default', null, 'error');
}
} else {
$this->data = $this->ReferralMedium->read(null, $id);
if (empty($this->data)) {
$this->cakeError('error404');
}
}
$this->pageTitle.= ' - ' . $this->data['ReferralMedium']['id'];
}
function admin_delete($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
if (is_null($id)) {
$this->cakeError('error404');
}
if ($this->ReferralMedium->del($id)) {
$this->Session->setFlash(__l('Referral Medium deleted') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->cakeError('error404');
}
}
}
?>
a model referral_model.php with the following content
<?php
class ReferralMedium extends AppModel
{
var $name = 'ReferralMedium';
var $useTable="referral_mediums";
//$validate set in __construct for multi-language support
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $hasOne = array(
'UserProfile' => array(
'className' => 'UserProfile',
'foreignKey' => 'referral_medium_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'UserProfile' => array(
'className' => 'UserProfile',
'foreignKey' => 'referral_medium_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->validate = array(
'referral_medium' => array(
'rule' => 'notempty',
'allowEmpty' => false,
'message' => __l('Required')
) ,
);
}
}
?>
a add view referral_mediums/admin_add.ctp with the following code
<?php /* SVN: $Id: $ */ ?>
<div class="referralMedium form">
<?php echo $form->create('ReferralMedium', array('class' => 'normal'));?>
<fieldset>
<h2><?php echo __l('Add Referral Medium');?></h2>
<?php
echo $form->input('referral_medium');
echo $form->input('is_active');
?>
</fieldset>
<div class="submit-block clearfix">
<?php echo $form->submit(__l('Add'));?>
</div>
<?php echo $form->end();?>
</div>
Now all works fine except if I click on the add button in the add form I get redirected to admin/referral_media/add instead of admin/referral_medium/add and I can't find the problem. I would be greatful I someone could help me with this.
the plural of medium is media, not mediums. The controller name is plural, so it's referral_media. So you'll need to change your controller name (and the file name).
Or change Config/bootstrap.php so it won't make controller names plural anymore.

Resources