Controller :
class gallery extends CI_Controller {
function index()
{
$this->load->model('gallery_model');
if($this->input->post('upload'))
{
$this->gallery_model->do_upload();
}
$data['images'] = $this->gallery_model->get_images();
$this->load->view('gallery',$data);
}
}
Model :
<?php
class gallery_model extends CI_Model {
var $gallery_path;
var $gallery_path_url;
function gallery_model()
{
$this->gallery_path = realpath(APPPATH . '../images');
$this->gallery_path_url = base_url().'images/';
}
function do_upload()
{
$config = array(
'allowed_types' => 'jpeg|jpg|gif|png',
'upload_path' => $this->gallery_path
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path. '/thumbs',
'maintain_ration' => TRUE,
'width' => 150,
'height' =>150
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}
View:
<!DOCTYPE html>
<html>
<head>
<title>My gallery</title>
<meta charset="UTF-8"/>
</head>
<body>
<div id="upload">
<?php
echo form_open_multipart('gallery');
echo form_upload('userfile');
echo form_submit('upload','Upload');
echo form_close();
?>
</div>
</body>
</html>
I want to do something like an photo album. In the upload form i upload photos in images folder and the thumb into thumb folder. What i want to do is to store the titles of pictures into the database and retrieve from there and i don't know how to store the pictures titles.
I would add a text field to your form for Image Title, pass it to your do_upload method from the gallery model, or separately into a new image database model (to connect and query your database).
I'm writing this on the fly and is untested. Some advice to the process, make sure you are cleaning the inputs. Codeigniter does a great job at this, but it's good coding to share that advice. Also, you should like an image with its title. I would maybe also pass to the database, the dir path of the image and/or its thumb path. It also makes calling the image from gallery easier as you are already querying the Database for meta data. Something like a foreach($img in$result){ echo $img['title']." - ".echo $img['path'];} to produce "My title - http://example.com/images/thumb/1234.jpg"
View (input)
..
echo form_input('imgTitle', 'Image Title');
..
Controller
..
if($this->input->post('upload'))
{
$data['imgTitle'] = $this->input->post('imgTitle'); //Assigns the post value to the data array so you can pass it via $data to your views
$this->gallery_model->do_upload($data['imgTitle']);
}
..
Model
..
function do_upload($imgTitle=null) //passes a variable as NULL unless specified
{
..
$DB1 = $this->load->database(); //specify db connection/name
$data = array(
'title' => $imgTitle, //passed from controller
'name' => 'My Name');
$this->db->insert('mytable', $data);
..
}
Related
I want to have the same name of image in database and in the image folder one I move. In folder is work but in database don't have ideas, can someone help me! Thanks
public function postRegister(Request $request) {
request()->validate([
'email' => 'required',
'password' => 'required|min:8',
'fullname'=>'required',
'birthday'=>'required',
'country'=>'required',
'address'=>'required|min:10',
'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
]);
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$data = $request->all();
// dd($image);
$check = $this->create($data);
return Redirect::to("login")->withSuccess('Great! You have Successfully loggedin');
}
If you want to set your image name to your db record.
Pass it to your $data before calling create method.
public function postRegister(Request $request) {
....
$data = $request->all();
$data['imageName'] = $file_name.".".$image->getClientOriginalExtension();
$check = $this->create($data);
return Redirect::to("login")->withSuccess('Great! You have Successfully loggedin');
}
If you want use mass assignment for save data you can use YourModelName::create(data).but you should pay attention to 2 thing .
first one define all fillable fields that you want allow to assign mass in your model class.so you should add your imageName field in fillable array .
second you should append yourImageName to your data that assign mass.like :data['yourImageField']=setvalue.
But if you want to assign row by row(its more safe and better i think) you should do like this: modelObject->Imagefield="imageName" and at end modelObject->save().
I'm a newcomer in CakePHP land.
I try to do the Post tutorial and added a extra table to the database.
I want to add record to the second table, the first table (posts) is working, but the second (cats) not.
It seems that the form is empty.
I don't get errors, it stays on the input page.
Is there somebody who can help?
VIEW
<?php
echo $this->Form->create('cat_cat');
echo $this->Form->input('naam_cat');
echo $this->Form->input('Omschrijving_cat', array('rows' => '3'));
echo $this->Form->input('image_cat', array('type' => 'file'));
echo $this->Form->end('Save Cat');
?>
CatsController
public function operation() {
if ($this->request->is('cat')) {
$this->Cat->create();
if ($this->Cat->save($this->request->data)) {
$this->Session->setFlash(__('Your cat has been saved.'));
return $this->redirect(array('action' => 'nosores2'));
}
$this->Session->setFlash(__('Unable to add your cat.'));
}
}
public function detail($id) {
if (!$id) {
throw new NotFoudExeption(__('Invalid cat'));
}
$cat = $this->Cat->findById($id);
if (!$cat) {
throw new NotFoundException(__('Invalid cat'));
$this->set('cat', $cat);
}
You need to use saveAll or saveAssociated if the Model is linked to another model.
Depends on how your tables look like
when you create a Form you need to put inside the name of the model:
echo $this->Form->create('Cat');
I've read through a couple posts which are really close to the same question I am about to ask, but I'm still not grasping the MVC way. One example was close and titled "Codeigniter db query on two tables", but I'm getting the "Undefined property" errors which reinforces that fact I'm not calling objects properly. I would prefer not to use DataMapper simply because if I need to go out and get additional classes, then I might just go back to the procedural coding route. I was just a little excited on understanding how this framework implementation works.
I have two tables, lets call one "apps" and the other would be "mappings". "Apps" are applications which use apache as a reverse proxy configuration like this:
ProxyPass /mapping/ https:///
ProxyPassReverse /mapping/ https:///
Some of the apps could request multiple reverse proxy mappings, so its a 1-many design.
My objective is to use a select statement for the apps table then print out every column I desire from that table:
for example, I currently have two application defined in my "apps" table, in which one of the applications has two reverse proxy mappings,and the other has one. The prxypass lines below the data from the apps table would be coming from the apps_mapping table.
App: App ABC
Owner: ABC Team
Date Requested: 2013-10-27
ProxyPass /ABC-Resource/ https://<to-some-internal-URL>/
ProxyPassReverse /ABC-resource/ https://<to-some-internal-URL>/
App: App XYZ
Owner: XYZ Team
Date Requested: 2013-10-27
ProxyPass /XYZ-mapping/ https://<to-some-internal-URL>/
ProxyPassReverse /XYZ-mapping/ https://<to-some-internal-URL2>/
ProxyPass /anothermapp/ https://<to-some-internal-URL>/
ProxyPassReverse /anothermapping/ https://<to-some-internal-URL2>/
I've tried to model my first attempt of using CodeIgniter by way of modifying their tutorial provided by the CodeIgniter example in their user_guide.
Now what I haveis.
Model Class:
<?php
class Prp_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//GET APP THE ROWs FROM THE apps TABLE
public function get_appsUsingPrp()
{
$query = $this->db->get('apps');
return $query->result_array();
}
//GET THE MAPPINGS FROM THE apps_mappings TABLE
//FOR EACH APP BY WAY OF UNIQUE id IN THE appsTABLE
public function get_prpMappings($id = FALSE)
{
$query = $this->db->get_where('apps_mappings', array('resourceID' => $id));
return $query->result_array();
}
?>
for the above class, instead of using a return function on get_prpMappings() should I be putting it in a variable? Even then, how would one supply a value for the $id in the code called int he views page?
Controller Class
<?php
class Prp extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('prp_model');
}
public function index()
{
$data['apps'] = $this->prp_model->get_prp();
$data['mappings'] = $this->prp_model->get_prpMappings($id);
$data['title'] = 'PRP archive';
$this->load->view('templates/header', $data);
$this->load->view('prp/index', $data);
$this->load->view('templates/footer');
}
public function view($id)
{
$data['apps'] = $this->prp_model->get_prp();
$data['mappings'] = $this->prp_model->get_prpMappings($id);
}
}
View
<?php
print_r($apps);
print_r($mappings);
foreach ($apps as $details): ?>
<div id="main">
<ul>
<?php echo "<li>App Name: ".$details['app_name'] ?>
<?php echo "<li>EPRID: ".$details['EPRID'] ?>
<?php echo "<li>Requestor: ".$details['requestor'] ?>
<?php echo "<li>Team PDL: ".$details['PDL'] ?>
<?php foreach ($mappings as $map): ?>
<?php echo "<li>ProxyPass /".$map['resource']."/ ".$map['destURL'] ?>
<?php echo "<li>ProxyPassReverse /".$map['resource']."/ ".$map['destURL'] ?>
<?php endforeach ?>
</ul>
</div>
<hr />
<?php endforeach ?>
?>
Getting down to my confusion.... Should I be doing all the foreach looping in the model and/or the controller classes if I'm not going to setup the DataMapper Class?
Is there a way to call the get_prpMappings($id) function defined in the model class directly in the view? The only way for that function to work for me, is when the id of the app row is provided when iterating through the rows.
I tried putting $this->prp_model->get_prpMappings($id); in the view, but the view page doesn't seem to identify the class.
Lastly.. By the looks of it, it appears I would be doing more coding with a framework (such as CodeIgniter or Zend), then it would be to just write everything from scratch. But I'm under the impression the framework is to provide convenience down the road of additional coding. I'm just not seeing it. Please help.
UPDATED! I hope I understand this.
I have modified my logic to express the output desired. Would you be able to tell me if it is an inefficient way? Here is the logic:
MODEL CLASS:
<?php
class Prp_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
//GET APP THE ROWs FROM THE sharedITG TABLE
public function get_appsUsingPrp()
{
$query = $this->db->get('sharedITG');
return $query->result_array();
}
//GET THE MAPPINGS FROM THE sharedITG_mappings TABLE
//FOR EACH APP BY WAY OF UNIQUE id IN THE shareITG TABLE
public function get_prpMappings($id = FALSE)
{
$this->db->select('resourceID, resource, destURL');
$query = $this->db->get_where('sharedITG_mappings', array('resourceID' => $id));
return $query->result_array();
}
public function get_prp()
{
//loop through all apps
foreach ($this->get_appsUsingPrp() as $app)
{
//print_r($app);
foreach ($this->get_prpMappings($app['id']) as $mappings)
{
$map[] = $mappings;
}
}
return $map;
}
}
Controller Class
<?php
class Prp extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('prp_model');
}
public function index()
{
$data['mappings'] = $this->prp_model->get_prp();
$data['apps'] = $this->prp_model->get_appsUsingPrp();
$data['title'] = 'PRP archive';
$this->load->view('templates/header', $data);
$this->load->view('prp/index', $data);
$this->load->view('templates/footer');
}
public function view($id)
{
$data['apps'] = $this->prp_model->get_appsUsingPrp();
$data['mappings'] = $this->prp_model->get_prp();
}
}
VIEW code:
<?php
//print_r($apps);
//print_r($mappings);
foreach ($apps as $details): ?>
<div id="main">
<ul>
<?php echo "<li>App Name: ".$details['app_name'] ?>
<?php echo "<li>EPRID: ".$details['EPRID'] ?>
<?php echo "<li>Requestor: ".$details['requestor'] ?>
<?php echo "<li>Team PDL: ".$details['PDL'] ?>
<?php
foreach ($mappings as $map)
{
if ($details['id'] == $map['resourceID'])
{
echo "<li>ProxyPass /".$map['resource']."/ ".$map['destURL'];
echo "<li>ProxyPassReverse /".$map['resource']."/ ".$map['destURL'];
}
}
?>
</ul>
</div>
<hr />
<?php endforeach ?>
So after further research, I found a forum that gave me a pretty decent example. I'm not sure if its the most optimal way to do this, but it worked for me and still (kind of) maintained the MVC model for Code igniter. The foreach in the function below is what I added. It appears it loops through the current result and obtains all rows for the second table that has a relationship between Table2ID and IDFromTable. Then adds the results by way of $result{$key}.
public function get_resuts()
{
$query = $this->db->get('table1');
$result = $query->result_array();
foreach ( $result as $key => $row )
{
$query = $this->db->get_where('Table2', array('Table2ID' => $row['IDFromTable']));
$row['DesiredFieldFromTable#'] = $query->result_array();
$result[$key] = $row;
}
return $result;
}
Then its available in the view by looping through the second array with the content from the foreach results in the get_resuts() function. I'm interested in learning of other ways to do this too.
I am making a Image link to user profile, but it is not working as it should be
this is my code.with this i want to add contoroller,function and id. How i can do it.
<?php
$pic = $User['User']['url'];
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), array('alt'=>$User['User']['handle'],'title' => $User['User']['handle']),array('escape'=>false) ,array('class'=>'inner_image'));
}else{
echo $this->Html->link($this->Html->image($User['User']['url']),array('alt' => $User['User']['handle']),array('escape'=>false),array('class'=>'inner_image'));
}
?>
This code is making image a link but i can't define a link and it is not accepting the class
.I want to pass this url
$this->Html->link('', array('controller'=>'User','action'=>'view','id'=>$User['User']['id']));
This is how I did it
echo $this->Html->link($this->Html->image($pic, array('class'=>'inner_image')), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false));
What cake version are you using? You don't seem to be following the documentation for Html::link.
HtmlHelper::link(string $title, mixed $url = null, array $options =
array(), string $confirmMessage = false)
alt, escape and class should be indexes in the options array, but you're not defininf the url parameter anywhere.
It should be something like this
if(!$pic){
echo $this->Html->link($this->Html->image('pro.jpg'), $url_array, array('alt'=>$User['User']['handle'],'title' => $User['User']['handle'],'escape'=>false,'class'=>'inner_image'));
} else {
echo $this->Html->link($this->Html->image($User['User']['url']), $url_array, array('alt' => $User['User']['handle'], 'escape'=>false, 'class'=>'inner_image'));
(don't know what url you want to point this at, so replace $url_array to your convenience.
I am using the Cakephp Google Map V3 Helper. I can get the google map to show up but the markers do not. Here is my view code:
<?php
echo $this->GoogleMapV3->map();
foreach ($allcondos as $condo) {
$options = array(
'lat' => $condo['Unit']['lat'],
'lng' => $condo['Unit']['lon']
);
$this->GoogleMapV3->addMarker($options);
}
?>
I know that if I just tell the app to echo out my $condo['Unit']['lat'] or ['lon'] it will do so in the foreach loop (so it is pulling my data). What I don't know how to do is how to write the code for the $options array. I have also tried this:
foreach ($allcondos as $condo) {
$lat=$condo['Unit']['lat'];
$lon=$condo['Unit']['lon'];
$options = array(
'lat' => $lat,
'lng' => $lon
);
$this->GoogleMapV3->addMarker($options);
}
How do I write this correctly?
A couple easy steps to get this to work:
Download
Download from https://github.com/dereuromark/cakephp-google-map-v3-helper and place the GoogleMapV3Helper.php file in /app/view/helper/GoogleMapV3Helper.php.
Load Helper
Either modify your appcontroller so that the top of it reads like the following:
<?php
class AppController extends Contoller{
public $helpers = array('Html','Javascript','GoogleMapV3');
}
?>
Or load it in a single controller by adding it to the helpers array as such:
<?php
class DemoController extends AppContoller{
function map() {
$this->helpers[] = 'GoogleMapV3';
# rest of your code
}
}
?
Include Scripts
Include Jquery in your header. Include the following as well:
<?php
echo '<script type="text/javascript" src="'.$this->GoogleMapV3->apiUrl().'"></script>';
?>
Create Map Container
Put this in your view where you want your map to appear. Feel free to modify the properties of the div.
<?php echo $this->GoogleMapV3->map(array('div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Note: you can change the default position of the map by including more options than just 'div':
<?php echo $this->GoogleMapV3->map(array('map'=>array(
'defaultLat' => 40, # only last fallback, use Configure::write('Google.lat', ...); to define own one
'defaultLng' => -74, # only last fallback, use Configure::write('Google.lng', ...); to define own one
'defaultZoom' => 5,
),'div'=>array('id'=>'my_map', 'height'=>'400', 'width'=>'100%'))); ?>
Add markers
Can be in a loop or whatever, but this is done in the view after your container is created.
<?php
$options = array(
'lat'=>40.770272,
'lng'=>-73.974037,
'title' => 'Some title', # optional
'content' => '<b>HTML</b> Content for the Bubble/InfoWindow' # optional
);
$this->GoogleMapV3->addMarker($options);
?>
note: only set the 'icon' key in the array if you want to use a custom image. Otherwise, they will not show up.
Include the script for the markers
<?php echo $this->GoogleMapV3->script() ?>
All done!
Alternately, you can use finalize() instead of script() if you do not want to echo the javascript right away, but write it to the buffer for later output in your layout:
<?php $this->GoogleMapV3->finalize(); ?>
See http://www.dereuromark.de/2010/12/21/googlemapsv3-cakephp-helper/ for details.