Generate The Auto Incrementig Number With Prefix Laravel - laravel-5.7

I have table named as product.The product table Consistis of the productcode field
and while adding the product I need to generte the code as PRO-1,PRO-2,PRO-3 in the sequence for the product code field and its must be loaded in the form

i have Created the function in my product model and succefully done this
public static function generateSeriesNumberWithPrefix($tableName = '', $autogenField = '', $autogenStart = '', $autogenPrefix = '')
{
$listFiledValues = DB::table($tableName)->select($autogenField)->get();
if ($listFiledValues->isEmpty())
{
$generatedAutogen = $autogenPrefix.$autogenStart;
return $generatedAutogen;
}
elseif ($listFiledValues->isNotEmpty())
{
foreach($listFiledValues as $listFiledValue)
{
$eachListarray = $listFiledValue->$autogenField;
$totalListArrays[] = $eachListarray;
}
foreach($totalListArrays as $totalListArray)
{
$stringRemovedEachListArray = substr($totalListArray,strlen($autogenPrefix));
$stringRemovedTotalListArray[] = $stringRemovedEachListArray;
}
$maximumValue = max($stringRemovedTotalListArray);
$generatedAutogen = $autogenPrefix.++$maximumValue;
return $generatedAutogen;
}
}
And Finally in the create function
public function create ()
{
$autogen = Product::generateSeriesNumberWithPrefix('product','autogen','1','PRO-');
return view('product.formadd', compact('result','sequence'));
}
I am using the Laravel Form builder So that
{!! Form::text('productcode', $autogen, null, ['class' => 'form-group']) !!}
here generateSeriesNumberWithPrefix is a function name and Product is a Model Name
Main Advantage of this function is it does not depend upon other fields such as created_ator the Max value in the primary keyit is standalone function

Related

Laravel change profile api gives null value

I am making change profile picture api in laravel .I want to update profile image in users table but not inserting or updating my images .Belew are my code please help me how to update user table .
fileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use App\Profile;
use Illuminate\Support\Facades\DB;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/files/' ;
$file->move($destinationPath,$fileName);
$updateuser->image = '/files/'.$fileName;
}
$updateuser->save();
return $updateuser;
}
}
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($request->hasFile('image'))
{
$filewithext = $request->file('image')->getClientOriginalName();
$ext = $request->file('image')->getClientOriginalExtension();
$fileToStrore = $filewithext;
$path = $request->file('image')->storeAs('public/files',$fileToStrore);
$updateuser->image = $fileToStrore;
}
$updateuser->save();
return $updateuser;
}
This code works for me. I hope it will work for you too...
Good Luck..
This code is working for me.....
fileUploadController.php
public function changeProfile(Request $request,$id){
$updateuser = User::find($id);
if ($request->hasFile('image')) {
$images = $request->file('image');
$destinationPath = public_path('files');
$imageName = time().'.'.$images->getClientOriginalExtension();
$images->move($destinationPath, $imageName);
$updateuser->image= $imageName;
}else{
$updateuser->image= '';
}
$updateuser->update();
return ['message' => 'Image Uploaded Successfully'];
}

Silverstripe 3.2: How to make a custom action button in the CMS to create a new Dataobject and populate it from another one

I'm searching for a way to create a custom action button which allows me to make a new DataObject with pre-filled content from another DataObject. As a simple example: When I have an email and click the "answer"-button in my email-client, I get a new window with pre-filled content from the email before. I need exactly this functionality for my button. This button should appear next to each DataObject in the GridField.
So I know how to make a button and add it to my GridField (--> https://docs.silverstripe.org/en/3.2/developer_guides/forms/how_tos/create_a_gridfield_actionprovider/) and I know how to go to a new DataObject:
Controller::curr()->redirect($gridField->Link('item/new'));
I also found out that there is a duplicate function for DataObjects:
public function duplicate($doWrite = true) {
$className = $this->class;
$clone = new $className( $this->toMap(), false, $this->model );
$clone->ID = 0;
$clone->invokeWithExtensions('onBeforeDuplicate', $this, $doWrite);
if($doWrite) {
$clone->write();
$this->duplicateManyManyRelations($this, $clone);
}
$clone->invokeWithExtensions('onAfterDuplicate', $this, $doWrite);
return $clone;
}
Perhaps it's easier than I think but at the moment I just don't get how to rewrite this to get what I need. Can somebody give me a hint?
That's for sure not the cleanest solution but I think it should do the trick.
At first let's create the custom gridfield action. Here we will save all accessible records in a session and add a query string to the url so that we'll know which object we want to "clone"
public function getColumnContent($gridField, $record, $columnName) {
if(!$record->canEdit()) return;
$field = GridField_FormAction::create(
$gridField,
'clone'.$record->ID,
'Clone',
'clone',
array('RecordID' => $record->ID)
);
$values = Session::get('ClonedData');
$data = $record->data()->toMap();
if($arr = $values) {
$arr[$record->ID] = $data;
} else {
$arr = array(
$record->ID => $data
);
}
Session::set('ClonedData', $arr);
return $field->Field();
}
public function getActions($gridField) {
return array('clone');
}
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'clone') {
$id = $arguments['RecordID'];
Controller::curr()->redirect($gridField->Link("item/new/?cloneID=$id"));
}
}
after adding this new component to our gridfield,
$gridField->getConfig()->addComponent(new GridFieldCustomAction());
we'll need to bring the data into the new form. To do so, add this code directly above "return $fields" on your getCMSFields function so it will be executed every time we'll open this kind of object.
$values = Session::get('ClonedData');
if($values) {
Session::clear('ClonedData');
$json = json_encode($values);
$fields->push(LiteralField::create('ClonedData', "<div id='cloned-data' style='display:none;'>$json</div>"));
}
At the end we need to bring the content back into the fields. We'll do that with a little bit of javascript so at first you need to create a new script.js file and include it in the ss backend (or just use an existing one).
(function($) {
$('#cloned-data').entwine({
onmatch: function() {
var data = JSON.parse($(this).text()),
id = getParameterByName('cloneID');
if(id && data) {
var obj = data[id];
if(obj) {
$.each(obj, function(i, val) {
$('[name=' + i + ']').val(val);
});
}
}
}
});
// http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript#answer-901144
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
})(jQuery);
And that's it ... quite tricky. Hope it will solve your problem.

SilverStripe convertDataObjectSet is stripping additional properties

I am attempting to add the 'AbsoluteLink' property to each DataObject in a DataList and then convert the list to JSON with JSONDataFormatter::convertDataObjectSet().
I have the following function:
public function json() {
$data = ResourceCentreArticlePage::get()->filter('ShowInMenus', '1')->filter('ShowInSearch', '1')->sort('Created', 'DESC');
$pageArray = new ArrayList();
foreach ($data as $page) {
$page->AbsoluteLink = $page->AbsoluteLink();
$pageArray->push($page);
}
// If I dump out the content of $pageArray here the object has the AbsoluteLink property
$jsonFormatter = new JSONDataFormatter();
$jsonData = $jsonFormatter->convertDataObjectSet($pageArray);
// If I dump out the content of $jsonData here there is no AbsoluteLink property
$this->response->addHeader("Content-type", "application/json");
return $jsonData;
}
The problem:
The AbsoluteLink property is removed after running the $pageArray through the convertDataObjectSet method.
What am I missing?
Using $jsonFormatter->setCustomAddFields(); will help here.
Add the following to the Page class:
public function getMyAbsoluteLink() {
return $this->AbsoluteLink();
}
For example to the Page.php:
class Page extends SiteTree {
public function getMyAbsoluteLink() {
return $this->AbsoluteLink();
}
}
And use that "magic field" like this:
public function json() {
$pages = Page::get()
->filter('ShowInMenus', '1')
->filter('ShowInSearch', '1')
->sort('Created', 'DESC');
$jsonFormatter = new JSONDataFormatter();
// add your custom field
$jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]);
$jsonData = $jsonFormatter->convertDataObjectSet(
$pages
);
return $jsonData;
}
Note the $jsonFormatter->setCustomAddFields(["MyAbsoluteLink"]); and I removed the array manipulation.
Also I removed your array manipulation. How the convertDataobjectSet function works it seems you can't amend the objects before it runs.

Validation on extended fields UserDefinedForm

I have made an extension on the UserDefinedForm (module userforms). This works well, but I cannot figure out how to set validation on this extra fields. This is (a part of) my code:
class UserDefinedPaymentForm_Controller extends UserDefinedForm_Controller {
private static $allowed_actions = array(
"finished",
"complete",
"error"
);
public function getFormFields() {
//Payment fields
$supported_methods = PaymentProcessor::get_supported_methods();
$gateways = array();
foreach ($supported_methods as $methodName) {
$methodConfig = PaymentFactory::get_factory_config($methodName);
$gateways[$methodName] = $methodConfig['title'];
}
$fields = parent::getFormFields();
$fields->add(new NumericField("PaymentAmount", _t('UserDefinedPaymentForm.PAYMENT_AMOUNT', 'Payment Amount')));
$fields->add(new Literalfield("literalfield", _t('UserDefinedPaymentForm.PAY', '<h2>Pay</h2>')));
$fields->add(new Literalfield("literalfield", _t('UserDefinedPaymentForm.PAY_INSTRUCTIONS', '<p>Choose your prefered payment method and click Pay:</p>')));
$fields->add(new DropdownField("PaymentMethod", _t('UserDefinedPaymentForm.PAYMENT_METHOD', 'Payment Method'), $gateways));
return $fields;
}
}
Now I want to validate the field PaymentAmount, the value of this field has to be 2 or more. How can I do this?
I would guess (I haven't tested this) your best bet is to create a subclass of UserFormValidator and override the php($data) method.
Then, in your UserDefinedPaymentForm_Controller, you will also need to override the Form method.
class PaymentAmountUserFormValidator extends UserFormValidator {
public function php($data) {
$result = parent::php($data);
if ($result === true) {
// verify your PaymentAmount here and return true or false, accordingly
}
return $result;
}
class UserDefinedPaymentForm_Controller {
...
public function Form()
{
$form = UserForm::create($this);
// Generate required field validator
$requiredNames = $this
->getController()
->Fields()
->filter('Required', true)
->column('Name');
$validator = new PaymentAmountUserFormValidator($requiredNames);
$form->setValidator($validator);
$this->generateConditionalJavascript();
return $form;
}
...
}

symfony 2 doctrine $query->getArrayResult() how to remove selected key->values from result

As I don't want id values from a select with createQuery, but the select command doesn't allow omitting id (primary key) from the actual query (using "partial") I need to remove the id's from the result from getArrayResult()
I made this small recursive key remover static class:
class arrayTool
{
public static function cleanup($array, $deleteKeys)
{
foreach($array as $key => $value )
{
if(is_array( $value))
{
$array[$key] = self::cleanup($array[$key], $deleteKeys);
} else {
if (in_array($key, $deleteKeys)) unset($array[$key]);
}
}
return $array;
}
}
Which is called by an array containing one or more keys to be removed from the result, of any array depth:
$array = arrayTool::cleanup($array, array('id', 'id2'));

Resources