How do I print the current date on Visualforce?
Stuff like Today(), System.now, doesn't work.
Haven't been able to find any documentation or stackoverflow questions regarding this subject.
Visualforce has Data and Time functions too, you can use {!NOW()} or {!TODAY()}.
For more details go here
In your controller, create a property:
public Date Today { get { return Date.today(); }}
In the VF page, try using:
<apex:outputText value="{0,date}">
<apex:param value="{!Today}" />
</apex:outputText>
Details on formatting the date can be found here and here.
Related
I'm making a simple booking system with the help of Laravel. The times that is booked is for an imaginary car company that rent cars. So you rent a car by booking the time. I'm pretty far into the project and I'm almost finished. I just have a small problem. I dont know how I can make my booked times "not bookable" so to say.
What I want to be unique is the date of the booking. In my migration for the "booked" times (the table is called "times") I have already set the column "date" to be unique:
public function up()
{
Schema::create('times', function (Blueprint $table) {
$table->integer('car_id')->unsigned();
$table->date('date');
$table->timestamps();
$table->primary(array('car_id', 'date'));
});
}
The date "integer" makes it so that it is unique and I can not book it twice. But what I want to do is check if the booked time is in the Carbon time frame of the ten days from present day. Those times is made like this:
$dt = Carbon::now('Europe/Stockholm');
for ($i = 0; $i < 10; $i++) {
$dates[$i] = $dt->addDays(1)->toDateString();
}
Then I send the $dates variable to my view and display them like this:
<ul class="list-group">
#foreach ($dates as $date)
<form method="POST" action="/{{ $car->id }}/time">
{{ csrf_field() }}
<li class="list-group-item">
<input type="hidden" name="date" value="{{ $date }}">
{{ $date }}
<input type="submit" value="Boka" class="btn btn-primary"/>
</li>
</form>
#endforeach
</ul>
So then if I press the "Boka" button the time is put in the "times" table, and because I use relationship I reach it with $car->time, like that I can get all the booked times on that specific car.
I show all the times that are booked like this in my view:
<ul class="list-group">
#foreach ($car->time as $time)
<li class="list-group-item">
{{ $time->date }}
<form method="POST" action="/delete/time/{{ $time->car_id }}/{{ $time->date }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger"/>
</form>
</li>
#endforeach
</ul>
So basically what I want to do now is to check if the date from Carbon is in the "times" table I want to remove the "Boka" button from the view..
My teacher tells me to use this code in some way:
$this->validate($request, [
'date' => 'exists:times,date'
]);
I know what this snippet of code does, it checks the request sent if the date from the form exist in the times table on the column date. But I just don't know where to use it. Ive tried in my "TimesController" where I add the dates to the "times" table like this:
public function update(Request $request, Car $car, Time $time) {
$this->validate($request, [
'date' => 'exists:times,date'
]);
$times = new Time;
$times->date = $request->date;
$car->time()->save($times);
return back();
}
But this doesn't work the way I want it to. It checks if the date is in the table, and if it is. It ads it. But the problem is, the date must be unique so I get an error message that says the date isn't unique. That's good but not what I want. So if I add a date that isn't booked yet. It doesn't add the date like it should. I check what error I get by writing this code in my view:
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
And the error it output said: "The selected date is invalid."
So what I get from that is that my validation code checks if the request is in the database then if it is, the date is added. But if the date isn't already in the "times" table it doesn't get added. That is the exact opposite of what I want..
I tried putting it in my CarsController to where I make up the dates with the help of Carbon as I showed earlier. But I just can't get anything out of that..
I know this post is kinda long. But I wanted to get as much information in as possible. I would really appreciate some help.
TL/DR: What I want to do is use the Validate function in Laravel to check if my dates for booking is in the booked "times" table or not. IF it is then I want the "Boka" button do disappear. The date shouldn't be able to be added to the "times" table. Alternatively the "date" could disappear entirely from the dates made with Carbon if it is in the "times" table...
I really don't know what to do so I would appreciate som help. Thanks.
And yeah, english isn't my native language so please don't bash me.
There are many ways to validate your data in Laravel. I will show you some of them, feel free to choose the one you'll like.
First of all, the basics.
You can use the validate method in the controller method of your choice. The official documentation has a nice example of it.
...
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
...
Your validation rule goes in the second parameter of the method, the array with other rules.
However, this is not the only way you can deal with validation.
As the documentation says in the "Other Validation Approaches" section, you can:
manually create a validator with Validator::make();
make a FormRequest to isolate your validation rules (and, eventually, logic) in a separate class;
Hope it helps. :)
Just check after validate method that if it returns true or false and based on that use return back with errors or proceed further.
I am eager to know how status of Product in Magento get changed/saved?
Requirement-:
Suppose there are existing products which are enabled in Magento...Now If admin Disable particular product from Backend then I need to catch that particular product's Id through code in Magento file system?
So from where Can I get disabled product's id in Magento code? What is the file location & function name for the same? how Can I get that particular id?
Please guide me...
I think the down voting here is a bit unfair. The op is only asking one question - how to get the product id and status of a product after it has been saved.
#Sam - in Magento, instead of finding the exact point in code where a product is being saved, you would typically hook into an event by creating a custom module and use the Magento event/observer facility from within that module.
Have a look through this tutorial which will guide you through the process of creating a module with event/observers: http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/customizing_magento_using_event-observer_method
Specifically related to your question: the event you are looking for is catalog_product_save_after.
The xml for your event would look similar to this:
<events>
<catalog_product_save_after>
<observers>
<yourmodule>
<class>Yourcompany_Yourmodule_Model_Observer</class>
<method>catalog_product_save_after</method>
</yourmodule>
</observers>
</catalog_product_save_after>
</events>
Your observer is going to look similar to this:
class Yourcompany_Yourmodule_Model_Observer
{
public function catalog_product_save_after($observer)
{
$product = $obvserver->getEvent()->getProduct();
$productStatus = $product->getStatus();
$productId = $product->getId();
}
}
Note - code is untested
I know that you can format a date like this:
<apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
<apex:param value="{!contact.Birthdate}" />
</apex:outputText>
However, my application will be distributed to multiple countries. On some (such as mine), date format is dd/MM/yyyy, but on others (such as in the US) the format is MM/dd/yyyy.
Is there a way I can tell Visualforce to use the locale's short date format?
The only solution to this issue that is actually working correctly was originally posted on http://mindfiresfdcprofessionals.wordpress.com/2013/10/25/how-to-dispaly-locale-formatted-datetime-in-visual-force/. I'm posting below code just in case the link will suddenly disappear:
You have to create new VF component called LocaleDate:
<apex:component access="global" controller="LocaleDateController">
<apex:attribute assignTo="{!dateValue}" description="The Date value to be rendered based upon the user's
locale" name="date_Value" type="Date"></apex:attribute>
{!TimeZoneValue}
</apex:component>
Its controller:
public with sharing class LocaleDateController {
public Date dateValue{get;set;}
public String getTimeZoneValue() {
if( dateValue != null ) {
String localeFormatT = dateValue.format();
return localeFormatT;
}
return null;
}
}
And then use such component like that:
<c:LocaleDate date_Value="{!TODAY()}"/>
It is working on any date value you enter, not necessarily sObject field. The whole idea is based on fact, that Date.format() function is creating String based on locale of current user. You can create in the same way wrapper controllers for DateTime and Decimal datatype.
Apex param based formating is based on Java's MessageFormat:
<apex:outputText value="{0, date, short}">
<apex:param value="{!contact.Birthdate}" />
</apex:outputText>
Assuming you are assigning the variable of type date in the value attribute, it should automatically handle the locale for you. So you don't need to format it explicitly.
I have a VF page which has 2 date fields and search button.
On click of search i get some results. i also have another button to print those results which is nothing but a new VF page rendered as pdf.
I want to pass this date values into the printVF page. i also want to have this page come up as popup.
I have the pageref with parameters set. Since i need to open this page as popup i need to find a way to use the pageref in the window.open.
Anybody has ideas on how to accomplish this?
Thanks
Prady
EDIT :What i did was build the url in the controller and use the controller variable in window.open. Something very strange is happening... The first time search results are displayed and i click the print button, the dates dont get populated in the string, they default to todays date.. if i again click the print button the dates are populated correctly on the url from the dateinput.
public Class1(){
System.debug('inside constructor');
fieldContainer=new DummyTable__c(); // it contains date fields for date inputs
date todays=date.today();
If (fieldContainer.Start_Date__c== null)
{
startdate1=todays;
}else
{
startdate1=fieldContainer.Start_Date__c;
}
If (fieldContainer.End_Date__c== null)
{
enddate1=todays;
}
else
{
enddate1=fieldContainer.End_Date__c;
}
}
public void search()
{
startdate1=fieldContainer.Start_Date__c;
system.debug('startdate1'+startdate1);
enddate1=fieldContainer.End_Date__c;
system.debug('enddate1'+enddate1);
system.debug('inside search()....after clicking search button');
system.debug('startdate1'+startdate1);
system.debug('url'+url);
LoadData();
}
public string geturl()
{
url='apex/VF1?Pstartdate='+string.valueof(startdate1)+'&Penddate='+string.valueof(enddate1);
return url;
}
public string geturlRec()
{
urlRec='apex/VF2?Pstartdate='+string.valueof(startdate1)+'&Penddate='+string.valueof(enddate1);
return urlRec;
}
VF Page
<script language="javascript" type="text/javascript">
function printOut()
{
window.open("{!url}");
}
function printIn()
{
window.showModalDialog("{!urlRec}","dialogWidth:800px; dialogHeight:200px; center:yes");
}
</script>
<div style="width:900px;margin:0 auto;" id="pagediv">
<span style="padding-left:30px;padding-right:10px">From </span><apex:inputfield value="{!fieldContainer.Start_Date__c}" id="startdt" style="padding-left:5px;padding-right:20px;"/>
<span style="padding-left:30px;padding-right:10px">To </span><apex:inputfield value="{!fieldContainer.End_Date__c}" id="enddt" style="padding-left:5px;padding-right:20px;"/>
<span style="padding-left:30px;padding-right:10px"><apex:commandButton action="{!search}" value="Search" ReRender="dtshipdep,dtshiprec,shippageblock"> </apex:commandButton></span>
<apex:commandButton action="{!saveDeparted}" value="Update " ReRender="dtshipdep"></apex:commandButton>
<apex:commandButton value="Print " onclick="printOut();"></apex:commandButton>
The salesforce recommended way to generate URLs is through URLFOR() function. Or, alternatively, you can create a PageReference in the extension/controller code.
Though, keep in mind, before any form data can become part of the URL it has to be posted to the server and come back in newly generated pageReference, for that reason you cannot jut click on it in the first run.
One way I used to solve this server side is using this code on VF
<apex:outputBlock rendered="{!openPopup}">
<script>
window.open('{!myTargetUrl}');
<script>
</apex:outputBlock>
openPopup is a bool that control whether this segment gets rendered (transient, you set it to true when you click on open button). myTarget is a PageReference based URL (alternatively you can use URLFOR here to generate URL in VF). If you have any more questions, ask.
Another option is to have your javascript code in VF which will pickup button click event and build the URL client side and open it up. You can use $Component to locate form fields.
You should be able to pass the values you need in the QueryString.
window.open("/apex/YourPage?VariableName=Value&SecondVariableName=SecondValue");
Then once you have the variables send to the new page, you can get them using a PageReference.
String myVariable = PageReference.getParameters().get('VariableName');
In my sample database table, I have a record with post id 999.
I got a few lines of code to retrieve the record of post id 999:
function viewing($sid){
$this->Testing->post_id=$sid;
$this->set('posts', $this->Testing->read());
}
But no record can be record retrieved from the post with id 999 when I altered the code:
function viewing($sid){
$sid=999;
$this->Testing->post_id=$sid;
$this->set('posts', $this->Testing->read());
}
Could you tell help me please?
You want to set the model::id attribute, not post_id.
$this->Site1->id=$sid;
I think you messing the terms and functions. First you set id of the Site1 model. Then you trying to read record from the Testing model and setting post_id in the record. The proper code should look like:
function viewing($sid){
$sid=999;
$this->Post->id=$sid;
$this->set('post', $this->Post->read());
}
Alternatively and more short it will be:
function viewing($sid){
$sid=999;
$this->set('post', $this->Post->read(null, $sid));
}
But assuming that you want to get posts probably the actual code should look like:
function viewing($sid){
$sid=999;
$this->set('post', $this->Posts->fund('all', array('conditions'=>array('post_id'=>$sid))));
}
Or something similar. I think first you should take a look on the CakePHP Cookbook and on the CakePHP API
Better to use the form $this->Post->read(null, $sid)
If you want to control retrieval of associated tables, use $this->MyModel->contain()
E.g.
$this->Post->contain('Testing') //(Post & Testing but not Site1)
or
$this->Post->contain('Testing','Site1.someValue') //(Post & Testing and Site1.someValue)
I think you should also carefully reread the manual sections on http://book.cakephp.org/view/78/Associations-Linking-Models-Together & http://book.cakephp.org/view/73/Retrieving-Your-Data