How to edit an image in laravel 5 if user upload a new one ,otherwise upload with old image file - image-processing

I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I want to just use the photo that's already in the database. And not update the image field at all. But in my code whenever I am trying to without uploading new image form is not taking the old input value.
Here is my edit function:
public function expenseupdate1(){
$input = Input::only('id','Expense_date','Expense_category_id','Vendor_id','Customer_id','Amount','Tax1_id','Tax2_id','Note','Receipt');
$data=new Expense;
$id=$input['id'];
$Expense_date=$input['Expense_date'];
$Expense_category_id=$input['Expense_category_id'];
$Vendor_id=$input['Vendor_id'];
$Customer_id=$input['Customer_id'];
$Amount=$input['Amount'];
$Tax1_id=$input['Tax1_id'];
$Tax2_id=$input['Tax2_id'];
$Note=$input['Note'];
if(Input::hasFile('Receipt')) {
$file = Input::file('Receipt');
$name = time() . '-' . $file->getClientOriginalName();
$data->Receipt = $name;
$file->move(public_path() . '/images/', $name);
}
$affectedrows=Expense::where('id', '=', $id)->update(array('Expense_date' => $Expense_date,'Expense_category_id'=>$Expense_category_id,'Vendor_id'=>$Vendor_id,'Customer_id'=>$Customer_id,'Amount'=>$Amount,'Tax1_id'=>$Tax1_id,'Tax2_id'=>$Tax2_id,'Note'=>$Note,'Receipt'=>$Receipt));
return redirect('expenseinfo');
}
and here is my update form image field code:
<td> <div class="form-group"style="margin-left:-305px">
{!! Form::label('image', 'Receipt') !!}
<input Input::old('Receipt'), type="file" name="Receipt" value = '{{$data->Receipt}}'></td><td><?php echo $data->Receipt; ?></td>
</div></td>
<tr>
<td>{!! Form::submit('Update', array( 'class'=>'' )) !!}
{!! Form::close() !!}</td>
Any help would be appreciated greatly

You wouldn't set a default value for file.
The file input type creates a field
through which users can upload files
from their local computer or network.
The VALUE attribute specifies the name
of the initial file, but it is
typically ignored by browsers as a
security precaution.
So, your application is behaving correctly. Since the image is already in the database you wouldn't need to uploaded it again.
Also, just FYI but you can clean up your controller method dramatically!
/**
* Update Expense 1
*
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function expenseupdate1(Request $request){
$expense = Expense::find($request->input('id'));
$expense->fill($request->only('id','Expense_date','Expense_category_id','Vendor_id','Customer_id','Amount','Tax1_id','Tax2_id','Note','Receipt'));
if($request->hasFile('Receipt')) {
$file = $request->file('Receipt');
$name = time() . '-' . $file->getClientOriginalName();
$expense->Receipt = $name;
$file->move(public_path('/images/'), $name);
}
$expense->save();
return redirect('expenseinfo');
}
The above assumes you have the necessary use statements at the top of you're controller i.e.
use Illuminate\Http\Request;
use App\Expense; //Assuming that Expense is in this namespace
If you haven't already, you should set the fillable array for you model to allow the fill() method (mass assignment) to work http://laravel.com/docs/5.1/eloquent#mass-assignment
There is even more you can do but I have already gone outside the scope of this question. I would, however, suggest looking at:
http://laravel.com/docs/5.1/routing#route-model-binding
http://laravel.com/docs/5.1/controllers#restful-resource-controllers
http://laravel.com/docs/5.1/controllers#dependency-injection-and-controllers
Hope this helps!

Related

TCPDF use within Cakephp

There are a lot posts about this subjects, but the link to any sloution are not working anymore... I followed this article.
I downloaded TCPDF master.
Upzipped it in the folder Vendor/ tcpdf
Eddited xtcpdf.php
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF{
}
Edit config.php (is this the right path?
/**
* Installation path (/var/www/tcpdf/).
* By default it is automatically calculated but you can also set it as a fixed string to improve performances.
*/
define ('K_PATH_MAIN', '/var/www/ppp/app/Vendor/tcpdf');
/**
* URL path to tcpdf installation folder (http://localhost/tcpdf/).
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
define ('K_PATH_URL', 'http://localhost/ppp/Vendor/tcpdf');
Create app/View/Layouts/pdf/default.ctp
<?php
header("Content-type: application/pdf");
echo $content_for_layout;
?>
Then in the webpages controller:
public function newpdf(){
$users = $this->User->find('all');
$this->set(compact('users'));
$this->layout = '/pdf/default';
$this->render()->type('application/pdf');
}
and in de view/webcontroller
public function newpdf(){
$users = $this->User->find('all');
$this->set(compact('users'));
$this->layout = '/pdf/default';
$this->render()->type('application/pdf');
}
When i want to test it i get a blank page, without anything...
I made the function in Webpages. Is that all right? Or should I make the function somewhere else?
The path in the configuration file, I work on a localhost on linux. The path: /var/www/ppp/app/Vendor/tcpdf. Is that the right path?
The URL is set is http://localhost/ppp/app/Vendor/tcpdf Is that the right URL?
Thanks in advance
first of all did you checked whether the tcpdf is loaded or not
App::import('Vendor','tcpdf',array('file' => 'tcpdf/tcpdf.php'));
then on path where you want to put the pdf.It must be the real path
$path=realpath('../webroot/pdf/') . '/';
then initialize the tcpdf
$pdf= new tcpdf();
then set desired file options
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle(title);
$pdf->SetSubject('TCPDF');
$pdf->SetKeywords(keywords);
// add a page
$pdf->AddPage();
then get the html which you want to convert to pdf
$html= $this->render('/Elements/Pdf');
write the html to pdf
$pdf->writeHTML($html, true, false, true, false, '');
then output it
$name='pdf.pdf';
$pdf->Output($path.$name, 'F');
Let me know if still have some issues.

Yii: Update model values before actionCreate and actionUpdate

I have a Location model with the following attributes -
id
City
State
Country
I wan't the user to be able to select from a list of existing states / countries, and if an additional item needs to be added it may be typed into a textbox. I've modified the _form.php partial as follows -
// city
<?php echo $form->textField($model,'city',array('size'=>60,'maxlength'=>100)); ?>
// state
<?php echo $form->dropDownList($model, 'state', CHtml::listData(Location::model()->findAll(), 'state', 'state')); ?>
<?php echo CHtml::textField('state2','',array('size'=>60,'maxlength'=>100)); ?>
// country
<?php echo $form->dropDownList($model, 'country', CHtml::listData(Location::model()->findAll(), 'country', 'country')); ?>
<?php echo CHtml::textField('country2','',array('size'=>60,'maxlength'=>100)); ?>
state2 and country2 are not a part of the model attributes. Now, in the Location Controller I have the following action -
public function actionCreate()
{
$model=new Location;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Location']))
{
$model->attributes=$_POST['Location'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
I want to set the values like this before this action executes -
if(!empty($_POST['state2'])) $model->state = $_POST['state2'];
if(!empty($_POST['country2'])) $model->country = $_POST['country2'];
What I've tried so far
1. Attempt 1
I added the lines directly to both actionCreate and actionUpdate. However, I don't think this is a clean solution.
1. Attempt 2
I tried adding a filter like this -
public function filterAlternateData($filterChain)
{
if(!empty($_POST['state2'])) $_POST['Location[state]'] = $_POST['state2'];
if(!empty($_POST['country2'])) $_POST['Location[country]'] = $_POST['country2'];
$filterChain->run();
}
Then I modified the filters() function like this so that it's bound to the create and update actions -
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'alternateData + create, update',
);
}
But this did not work.
Anyone have any ideas?
I presume this is happening in a CRUD operation based upon the actionCreate() method.
Personally I would create a separate form for the create functionality with the following attributes.
Form
Cities
States
Countries
New city (not required)
New State (not required)
New Country (not required)
Then in the form validation you can check to see if the user has entered a city, state or country which already exists etc.
You can add the lines in beforeSave() method (you will have to override it) of your model.

SugarCRM: Coding a Custom Middle Name field

I'm trying to create a Custom Field in SugarOS 6 to store Middle Names. Designing and implementing the field in EditView was easy enough with the Studio. But I'm stuck when it comes to displaying the concatenated name parts in DetailView (i.e. Salutation + First Name + Middle Name + Last Name).
Foraging through the Sugar Forums got me to this thread which describes a way it can be done. I've implemented the code given there in the form of a Sugar logic hook that utilizes the after_retrieve hook that is called upon the loading of a record.
Here's my hook code:
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = array(
100,
'set_full_name',
'custom/modules/Leads/leads_custom_logic.php',
'LeadsCustomLogic',
'setFullName'
);
And here's the function that is being called:
function setFullName( &$focus, $event, $arguments ) {
$name = $focus->salutation . ' ' .
$focus->first_name . ' ' .
( $focus->middle_name_c ? ( $focus->middle_name_c . ' ' ) : '' ) .
$focus->last_name;
$focus->name = $name;
$focus->full_name = $name;
// echo $focus->full_name;
}
The hook and the called code seems to work fine and if I uncomment the last line (echo) the full name is dumped all over the screen (wherever this function is called). However, it's not displaying where it's actually supposed to, i.e. the row in the DetailView screen where the full name appears.
Any ideas?
Thanks,
m^e
maybe just change detailview.php and add the following to your full name field defs
'customCode' => '{$fields.salutation.value} {$fields.first_name.value} {$fields.midle_name_c.value} {$fields.last_name.value}'
as a new key => value in array and the custom code will be displayed instead of full_name value.

How to display extra fields in article with K2

currently I've got Jreviews installed and I'd like to replace it by K2 to list specialized shops with addresses, phones, maps, opening hours ...
With K2 I guess I'll need to define extra custom fields to hold those specific information. No problem.
But, how may I configure things to have those fields displayed in the detailed article/items for a specific shop ?
Many thanks,
Tibi.
// In the item template you can skip this first line...
$this->item->extra_fields = K2ModelItem::getItemExtraFields($this->item->extra_fields);
$extraFlds = array();
if ( $this->item->extra_fields ){
foreach ( $this->item->extra_fields as $key=>$extraField ){
$extraFlds[ $extraField->name ] = $extraField->value;
}
}
Then you can access your extra fields in the associate array like $extraFlds['my field']
After a lot of tries here what i used and worked for me
<?php
// if form is empty show default form
$k2obj = new K2ModelItem();
$fields = $k2obj->getItemExtraFields($this->item->extra_fields, $this->item);
//echo $this->item->extraFields->State->name;
echo $this->item->extraFields->FIELD_ALIAS->value;
?>
This is working and noted its all pegged to instantiating the class.
Note: I am using this in the k2 item i version 2.6.7 Joomla 2.5.14
if you want show custum field in k2 table list go to:
components\com_k2\templates\default\category_item.php
and edit file near line 136 like this:
<?php foreach ($this->item->extra_fields as $key=>$extraField):
**if(strpos($extraField->name,"/")){**
?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<span class="catItemExtraFieldsLabel"><?php echo $extraField->name; ?></span>
<span class="catItemExtraFieldsValue"><?php echo $extraField->value; ?></span>
</li>
<?php **}** endforeach; ?>
i do that in my site: www.joomir.com
The problem is that $this->item->extra_fields is actually a JSON string retrieved from the database, so you have to decode it first. It's structure is rather complicated (and unfortunately each field is labelled by it's id, it's name doesn't appear at all), you'll see it if you execute:
print_r($this->item->extra_fields);`
If you want to call field values by it's field name I'd do it like this:
if ($this->item->params->get('itemExtraFields')) {
$item_extra_fields = json_decode($this->item->extra_fields);
$put_your_extra_field1_name_here = $item_extra_fields[1]->value;
$put_your_extra_field2_name_here = $item_extra_fields[2]->value;
$put_your_extra_field3_name_here = $item_extra_fields[3]->value;
$put_your_extra_field4_name_here = $item_extra_fields[4]->value;
}
Notice that this is useful if the extra field you need is text, but it can be an array or whatever so you might have to code a little bit more. Hope this is useful!
In K2 you set the parameters for how an item displays at the category level. There is an option to display the extra fields in both Item view options in category listings as well as the Item view options.
By default, the built in K2 template will display the extra fields under a heading "Additional Information" with an unordered list of field name and values. You can override that template and make the extra fields display any way you like.

Get fragment (value after hash '#') from a URL [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP?     => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
                                    YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..

Resources