save image with cakephp3 - image

I want to save the image path through a form, but the path of the image is not saved.
i've tried with this but i don't know where to put the code
MultimediaController:
public function add()
{
$multimedia = $this->Multimedia->newEntity();
if ($this->request->is('post')) {
$multimedia = $this->Multimedia->patchEntity($multimedia, $this->request->data);
$file = $_FILES['url'];
$path = 'files/' .$_FILES['url']['name'];
move_uploaded_file($this->data['url']['tmp_name'], $path);
if ($this->Multimedia->save($multimedia)) {
$this->Flash->success('The multimedia has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The multimedia could not be saved. Please, try again.');
}
}
$categories = $this->Multimedia->Categories->find('list', ['limit' => 200]);
$this->set(compact('multimedia', 'categories'));
$this->set('_serialize', ['multimedia']);
}
add.ctp
<?= $this->Form->create($multimedia, array('enctype' => 'multipart/form-data')); ?>
<fieldset>
<legend><?= __('Add Multimedia') ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('description');
echo $this->Form->input('mime_type');
echo $this->Form->input('filename');
echo $this->Form->input('url', array('type' => 'file'));
echo $this->Form->input('category_id', ['options' => $categories]);
echo $this->Form->input('created_by');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I'm new to cakephp 3 and am a bit lost. Please help.
Update:
already achieved to save the image:
$file = $_FILES['url'];
$path = "webroot\\files\\" .$_FILES['url']['name'];
print_r($file);
move_uploaded_file($_FILES['url']['tmp_name'], $path);
if ($this->Multimedia->save($multimedia)) {
$this->Flash->success('The multimedia has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The multimedia could not be saved. Please, try again.');
}
But now the "url" is not saved in the database

I hope this help you, the script here has some improvements like using the short deceleration for arrays:
The Controller code:
//don't forget to import the Folder class
use Cake\Filesystem\Folder;
public function add()
{
$multimedia = $this->Multimedia->newEntity();
if ($this->request->is('post')) {
$multimedia = $this->Multimedia->patchEntity($multimedia, $this->request->data);
//upload script start here
$mm_dir = new Folder(WWW_ROOT . 'upload_dir', true, 0755);
$target_path = $mm_dir->pwd() . DS . $this->request->data('url.name');
move_uploaded_file($this->request->data('url.tmp_name'), $target_path);
//save the file name in the field 'url'
$multimedia->url= $this->request->data('url.name');
//the script ends here
if ($this->Multimedia->save($multimedia)) {
// ............
} else {
// .........
}
}
// ..........
}
add.ctp // improvement
<?= $this->Form->create($multimedia, ['type' => 'file']); ?>
echo $this->Form->input('url', ['type' => 'file']);

Related

Codeigniter-login with session

i am trying to do a login with sessions but it doesn't seem to be working because when i log in the session data on the view is not being displayed. once logged in it should read something like: 'Welcome Jon' but it doesn't. What could be the issue
controller fn
function login_user()
{
if(isset($_POST['login']))
{
$data = $this->Model_students->fetchUserData();
if(!empty($data))
{
var_dump($data);
foreach ($data as $key => $value) :
$user_id = $value->id;
$firstname = $value->firstname;
$lastname = $value->lastname;
$grade = $value->grade;
$email = $value->email;
$images = json_decode($value->userfile);
endforeach;
$user_info = array(
'id' => $user_id,
'firstname' => $firstname,
'lastname' => $lastname,
'grade' => $grade,
'email' => $email,
'images' => $images[0]->file_name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($user_info);
redirect('Students/homepage');
}
else
{
$this->session->set_flashdata('error', 'Error! Invalid username or password');
redirect('Students/login_user');
}
}
else
{
$this->load->view('signup');
}
}
model
the join here is for a different table in the same db where the common row is id..not sure if the join is correct too
public function fetchUserData()
{
$this->db->select('users.*, user_images.*');
$this->db->from('users');
$this->db->join('user_images', 'users.id=user_images.user', 'inner');
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get();
if($query->num_rows() == 1 ) :
foreach($query->result() as $row):
$data[] = $row;
endforeach;
return $data;
endif;
}
view the img scr here should display the user image based on what is saved on the db when he/she first registered
</head>
<body>
<h3>Welcome <?php $this->session->userdata('$firstname')?>.</h3>;
<img class ="img-circle" src="<?=base_url();?>uploads/users/<?=$this->session->userdata('userfile/file_name');?>" width="250" height="auto">
There's a typo in your views. where the session variable should be without the $ symbol.
<h3>Welcome <?php echo $this->session->userdata('firstname'); ?>.</h3>;
Also, check if the $user_info contains the expected data. Do a var_dump($user_info) and see just before creating the session.
there could be many issues with it.
1: your are passing a variable in the string which is not valid ( $this->session->userdata('$firstname') ) remove the $ from the first name;
2: there has to be a constructor in the controller so that the session could be called when ever the object is created;
hope it will solve your problem

Codeigniter User's Data

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

Fatch value in Dependent dropdown in Yii2

I created a Dependent drop-down now i want to fetch these values on update page. How can i do ?
I created 2 drop-down - 1st Client and 2nd Staff
on update page i got the value of client but i did not get the value of staff (Because it is dependent drop-down)
Form
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists&id=')).'"+$(this).val(), function( data )
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')
->dropDownList
(
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
Controller
public function actionLists($id)
{
$sql = "select * from staff where client='$id' ";
//exit;
$models = Staff::findBySql($sql)->asArray()->all();
//echo "<pre>";print_r($model);exit;
if(sizeof($models) >0){
echo "<option>-Choose a Sub Category-</option>";
foreach($models as $model){
echo "<option value='".$model['id']."'>".$model['fname']."</option>";
}
}
else{
echo "<option>-Choose a Sub Category-</option><option></option>";
}
}
first add $modelsStaff variable to your create and update actions like below:
<?
public function actionCreate()
{
$modelsStaff=null;
$model = new model();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
$sql = "select * from staff where client='$model->client'";
$modelsStaff = Staff::findBySql($sql)->asArray()->all();
return $this->render('update', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
?>
In your update action find all staff using $model->client and get all staff under this client and update your view like this
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists?id=')).'"+$(this).val(), function( data ) //<---
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')->dropDownList
($modelsStaff,
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
You have to create separate function in your controller (like an example):
public function actionLists($id)
{
$posts = \common\models\Post::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if (!empty($posts)) {
$option = '<option>-Select Option-</option>';
foreach($posts as $post) {
$options .= "<option value='".$post->id."'>".$post->title."</option>";
}
return $options;
} else {
return "<option>-</option>";
}
}
and in view file (example):
use yii\helpers\ArrayHelper;
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'category_id')->dropDownList($dataCategory,
['prompt'=>'-Choose a Category-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('post/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title');
echo $form->field($model, 'title')
->dropDownList(
$dataPost,
['id'=>'title']
);
This is from Yii docs: https://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2

CakePHP 3.1 : My validation for translate behaviour fields, need some help in review/comment

I have worked on a hook for validate my translated fields, based on this thread : https://stackoverflow.com/a/33070156/4617689. That i've done do the trick, but i'm looking for you guys to help me to improve my code, so feel free to comment and modify
class ContentbuildersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Tree');
$this->addBehavior('Timestamp');
$this->addBehavior('Translate', [
'fields' => [
'slug'
]
]);
}
public function validationDefault(Validator $validator)
{
$data = null; // Contain our first $context validator
$validator
->requirePresence('label')
->notEmpty('label', null, function($context) use (&$data) {
$data = $context; // Update the $data with current $context
return true;
})
->requirePresence('type_id')
->notEmpty('type_id')
->requirePresence('is_activated')
->notEmpty('is_activated');
$translationValidator = new Validator();
$translationValidator
->requirePresence('slug')
->notEmpty('slug', null, function($context) use (&$data) {
if (isset($data['data']['type_id']) && !empty($data['data']['type_id'])) {
if ($data['data']['type_id'] != Type::TYPE_HOMEPAGE) {
return true;
}
return false;
}
return true;
});
$validator
->addNestedMany('translations', $translationValidator);
return $validator;
}
}
I'm not proud of my trick with the $data, but i've not found a method to get the data of the validator into my nestedValidator...
Important part here is to note that i only rule of my nestedValidator on 'translations', this is very important !
class Contentbuilder extends Entity
{
use TranslateTrait;
}
Here basic for I18ns to work
class BetterFormHelper extends Helper\FormHelper
{
public function input($fieldName, array $options = [])
{
$context = $this->_getContext();
$explodedFieldName = explode('.', $fieldName);
$errors = $context->entity()->errors($explodedFieldName[0]);
if (is_array($errors) && !empty($errors) && empty($this->error($fieldName))) {
if (isset($errors[$explodedFieldName[1]][$explodedFieldName[2]])) {
$error = array_values($errors[$explodedFieldName[1]][$explodedFieldName[2]])[0];
$options['templates']['inputContainer'] = '<div class="input {{type}} required error">{{content}} <div class="error-message">' . $error . '</div></div>';
}
}
return parent::input($fieldName, $options);
}
}
With that formHelper we gonna get the errors of nestedValidation and inject them into the input, i'm not confortable with the templates, so that's why it's very ugly.
<?= $this->Form->create($entity, ['novalidate', 'data-load-in' => '#right-container']) ?>
<div class="tabs">
<?= $this->Form->input('label') ?>
<?= $this->Form->input('type_id', ['empty' => '---']) ?>
<?= $this->Form->input('is_activated', ['required' => true]) ?>
<?= $this->Form->input('translations.fr_FR.slug') ?>
<?= $this->Form->input('_translations.en_US.slug') ?>
</div>
<?php
echo $this->Form->submit(__("Save"));
echo $this->Form->end();
?>
Here my fr_FR.slug is required when type_id is not set to Type::TYPE_HOMEPAGE, yeah my homepage has not slug, note that the en_US.slug is not required at all, because i only required 'translations.xx_XX.xxxx' and not '_translations.xx_XX.xxxx'.
And the last part of the code, the controller
$entity = $this->Contentbuilders->patchEntity($entity, $this->request->data);
// We get the locales
$I18ns = TableRegistry::get('I18ns');
$langs = $I18ns->find('list', [
'keyField' => 'id',
'valueField' => 'locale'
])->toArray();
// Merging translations
if (isset($entity->translations)) {
$entity->_translations = array_merge($entity->_translations, $entity->translations);
unset($entity->translations);
}
foreach ($entity->_translations as $lang => $data) {
if (in_array($lang, $langs)) {
$entity->translation($lang)->set($data, ['guard' => false]);
}
}
Here a .gif of the final result om my side : http://i.giphy.com/3o85xyrLOTd7q0YVck.gif

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

Resources