Using IF condition to populate a new sheet in Google App Script Spreadsheet - vba

I have a Google Spreadsheet containing 2 sheets.
If the content of a specific cell in sheet 1 is equal to something, I want to write something in a specific cell of the sheet 2.
As I need to do it a lot of times, I want to do it using Google App Script. Using VBA, this is super easy, but here it returns me that I "can't change or modify the properties of the object". Do you have any idea of what's wrong with my code?
Thank you for your help !
Here is my code :
function synthese() {
var results = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('results');
var synthese = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('synt');
B3 = results.getRange("B3");
if (B3="Yes") {
results.getRange("A1").setValue = "Yes";
} else {
results.getRange("A1").setValue = "No";
}
}

B3 is still a range, with properties such as size, background color, etc.
It is not a value, you can extract that via getValue().
Your second problem is that you are doing an assignment in the if.
Lastly setValue is a method not an attribute, so the value needs to be supplied as an argument.
function synthese() {
var results = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('results');
var synthese = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('synt');
var B3 = results.getRange("B3"); // good practice to make variables local
if (B3.getValue() === "Yes") {
results.getRange("A1").setValue("Yes");
} else {
results.getRange("A1").setValue("No");
}
}

Related

Epplus LoadFromCollection header from class members

I am trying to create an excel file using Epplus package. I am doing this
static List<TestData> list = new List<TestData>
{
new TestData
{
Name = "Mohsin",
Number = 1
},
new TestData
{
Name = "Ali",
Number = 2
}
};
I am then calling this function
sheet.Cells["A1"].LoadFromCollection(list, true);
I saves the correct data to the file but missing headers and I want the members of my class to be the header here. Is there a way I can achieve it without hard coding? As I would be calling it from various different types of object types?
It's working for me like this:
sheet.Cells["A1"].LoadFromCollection(Collection: res, PrintHeaders: true);
also you may like this:
sheet.Cells["A1"].LoadFromCollection(list, true);
Probably you have some missing in your output file.

Use filtered dataProvider contents when FileDownloader is called in Vaadin

I'm trying to download a csv file after applying filters to the DataProvider.
For some reason the filtered results are shown in the Grid, but the downloaded csv file still contains all data.
#AutoView
class FinancialTransactionsView : VerticalLayout(), View {
private val grid: Grid<FinancialTransaction>
private val yearField: ComboBox<Int>
private val dataProvider = DataProvider.ofCollection(FinancialTransaction.findAll())
private val fileDownloader: FileDownloader
init {
label("Financial Transactions") {
styleName = ValoTheme.LABEL_H1
}
yearField = comboBox("Select Year") {
setItems(listOf(2016, 2017, 2018))
addSelectionListener {
// Filter the data based on the selected year
if (it.value != it.oldValue) setDataProvider()
}
}
// Create FileDownloader and initialize with all contents in the DataProvider
fileDownloader = FileDownloader(createCsvResource())
val downloadButton = button("Download csv") {
styleName = ValoTheme.BUTTON_PRIMARY
onLeftClick {
// The idea here is to assign values from the filtered DataProvider to the FileDownloader
fileDownloader.fileDownloadResource = createCsvResource()
}
}
fileDownloader.extend(downloadButton)
fileDownloader.fileDownloadResource = createCsvResource()
grid = grid(dataProvider = dataProvider) {
expandRatio = 1f
setSizeFull()
addColumnFor(FinancialTransaction::companyId)
addColumnFor(FinancialTransaction::fiscalYear)
addColumnFor(FinancialTransaction::fiscalPeriod)
addColumnFor(FinancialTransaction::currency)
addColumnFor(FinancialTransaction::finalizedDebitAmountInCurrency)
addColumnFor(FinancialTransaction::finalizedCreditAmountInCurrency)
appendHeaderRow().generateFilterComponents(this, FinancialTransaction::class)
}
}
private fun createCsvResource(): StreamResource {
return StreamResource(StreamResource.StreamSource {
val csv = dataProvider.items.toList().toCsv()
try {
return#StreamSource csv.byteInputStream()
} catch (e: IOException) {
e.printStackTrace()
return#StreamSource null
}
}, "financial_transactions.csv")
}
private fun setDataProvider() {
dataProvider.clearFilters()
if (!yearField.isEmpty)
dataProvider.setFilterByValue(FinancialTransaction::fiscalYear, yearField.value)
}
}
toCsv() is an extension function List<FinancialTransaction> which returns a string containing csv data.
What can I do to get the filtered results in my csv file?
val csv = dataProvider.items.toList().toCsv()
I am not Kotlin guy, but I assume dataProvider.items is a shorthand to dataProvider.getItems() in Java, i.e. this method (and you use ListDataProvider)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/ListDataProvider.html#getItems--
In Vaadin getItems() returns all items by passing all filters.
So instead you should do either of the following
dataProvider.fetch(..)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/DataProvider.html#fetch-com.vaadin.data.provider.Query-
Where you give the filters you want to apply in the query, or
grid.getDataCommunicator.fetchItemsWithRange(..)
https://vaadin.com/download/release/8.4/8.4.1/docs/api/com/vaadin/data/provider/DataCommunicator.html#fetchItemsWithRange-int-int-
Which returns list of items with filters you have set applied, which I think is ideal for you
Thank you for using Vaadin-on-Kotlin!
I've just updated the Databases Guide which should hopefully answer all of your questions. If not, just let me know and I'll update the guides accordingly.
The ListDataProvider.items will not apply any filters and will always return all items.
You need to use the getAll() extension function in order to obey the filters set by the Grid.
This is now explained in the Exporting data from DataProviders chapter of the Databases Guide.
In your code, both the grid and the yearField will set the filter to the same data provider,
thus overwriting values set by each other. Please read the Chaining Data Providers chapter in the Databases Guide to learn how to AND multiple filters set by multiple components.
When you use private val dataProvider = DataProvider.ofCollection(FinancialTransaction.findAll()), that will load all transactions from the database in-memory. You can use a more memory-efficient way: private val dataProvider = FinancialTransaction.dataProvider (given that FinancialTransaction is an Entity)
Please let me know if this answers your questions. Thanks!

Javafx Hyperlink parameters on action

Thank you for reading my question and apologies for the noobness
I am writing my first JavaFX application in which I have an array of hyperlinks which have latitude longitude (e.g. "42N 7E") in the text value of the hyperlink which is being updated every second from another Thread and updates the hyperlink text in the Main Thread. (This works fine)
public static void setPosLatLong(String posLatLong, int SID) {
Main.posLatLong[SID].setText(posLatLongValue);
}
I am trying to use the value in the hyperlink text when clicking on the hyperlink to dynamically change the destination URL with the latest latlong values... but I get the error 'local variables referenced from a lambda expression must be final or effectively final'
int SID = 'id of the hyperlink corresponding to a machine'
posLatLong[SID] = new Hyperlink();
posLatLong[SID].setOnAction((ActionEvent event) -> {
getHostServices().showDocument("http://maps.google.com/maps?z=17&q=" + posLatLong[SID].getText());
});
I have tried all kinds of ways to get around this but I am shamefully stuck. If anyone could point me in the right direction so that the last updated value in the hyperlink array is passed as a parameter when opening the browser it would be greatly appreciated.
I think I managed to find a solution myself so I'll post it in case it could be useful to someone
posLatLong[i].setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String eventLatLong = "";
Object source = event.getSource();
if (source instanceof Hyperlink) {
Hyperlink link = (Hyperlink) source;
eventLatLong = link.getText();
}
getHostServices().showDocument("http://maps.google.com/maps?z=17&q=" + eventLatLong );
}
});
Tada !

my zend session name spacing does not work

I am new to Zend and very keen to learn, so I would really appreciate some help and guidance.
I am trying to create a 'method in a class' that will save the session variables of product pages visited by members to a site i.e
i,e examplesite com/product/?producttype= 6
I want to save the number 6 in a session variable. I also do not want to have a global session for the entire site; I just want it for selected pages. So, I guess I have to have Zend_Session::start() on the selected page; but I am not clear how this should be done.
Should I instantiate it in the page view page. i.e products page or do this in the indexAction() method for the products page. I have attempted to instantiate it below but it did not work.
public function rememberLastProductSearched()
{ //my attempt to start a session start for this particular page.
Zend_Session::start();
}
$session->productSearchCategory = $this->_request->getParam('product-search-category');
return" $session->productSearchCategory ";
}
else
{
//echo " nothing there
return " $session->productSearchCategory";
//";
}
}
With the rememberLastProductSearched() method I was trying to get the method to first check whether the user had searched for a new product or just arrived at the page by default. i.e whether he had used the get() action to search for a new product. If the answer is no, then I wanted the system to check whether their had been a previous saved session variable. so in procedural syntax it would have gone like this:
if(isset($_Get['producttype']))
{
//$dbc database connection
$producttype = mysqli_real_escape_string($dbc,trim($_GET['producttype']));
}
else
if(isset($_SESSION['producttype'])){
$producttype = mysqli_real_escape_string($dbc,trim($_SESSION['producttype']));
}
Can you please help me with the Zend/oop syntax. I am totally confused how it should be?
you're asking about simple work flow in an action, it should begin something like:
//in any controller
public function anyAction()
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
//get value
$productCategory = $this->getRequest()->getParam('producttype');
//save value to namespace
$session->productType = $productCategory;
//...
}
now to move this off to a separate method you have to pass the data to the method...
protected function rememberLastProductSearched($productType)
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
$session->productType = $productType;
}
So now if you want to test for presence of a value...
//in any controller
public function anyAction()
{
//open seesion, call the namespace whenever you need to access it
$session = new Zend_Session_Namespace('products');
if (!isset($session->productType)) {
$productCategory = $this->getRequest()->getParam('producttype');
//save value to session
$this->rememberLastProductSearched($productCategory)
} else {
$productCategory = $session->productType;
}
}
That's the idea.
Be mindful of your work flow as it can sometimes be very simple to inadvertently overwrite your session values.
$session = new Zend_Session_Namespace("productSearch");
if ($this->getRequest()->getParam('producttype')) { //isset GET param ?
$session->productType = $this->getRequest()->getParam('producttype');
$searchedProductType = $session->productType;
} else { //take the session saved value
if ($session->productType) {
$searchedProductType = $session->productType;
}
}
//now use $searchedProductType for your query

My Nintex Custom Action not reading in Workflow Variable in SingleLineInput

I've written a custom workflow action that takes in several values, mostly using the SingleLineInput control.
When I assign literal values, I have no issues, but when I try to assign a Workflow Variable, I don't get the actual value of the variable, I get the literal text - something like {WorkflowVariable:XmlValue} - assuming my variable was names XmlValue.
I'm not sure what I could possibly be doing wrong. Any ideas?
Here's code snippets:
The javascript for retrieving the value from the SingleLineInput
function TPAWriteConfig() {
configXml.selectSingleNode("/NWActionConfig/Parameters/Parameter[#Name='FieldValue']/PrimitiveValue/#Value").text = getRTEValue('<%=fieldValue.ClientID%>');
SaveErrorHandlingSection();
return true;
}
The server control:
<Nintex:ConfigurationProperty ID="ConfigurationProperty3" runat="server" FieldTitle="Field Value" RequiredField="True">
<TemplateControlArea>
<Nintex:SingleLineInput runat="server" id="fieldValue"></Nintex:SingleLineInput>
</TemplateControlArea>
</Nintex:ConfigurationProperty>
From my adapter class:
private const string FieldValueProperty = "FieldValue";
NWActionConfig config = new NWActionConfig(this);
config.Parameters[2] = new ActivityParameter();
config.Parameters[2].Name = FieldValueProperty;
config.Parameters[2].PrimitiveValue = new PrimitiveValue();
config.Parameters[2].PrimitiveValue.Value = string.Empty;
config.Parameters[2].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
From the activity class:
public static DependencyProperty FieldValueProperty = DependencyProperty.Register("FieldValue", typeof (string),
typeof (
WriteOnePdfFieldActivity));
public string FieldValue
{
get { return (string) GetValue(FieldValueProperty); }
set { SetValue(FieldValueProperty, value); }
}
I feel a little silly answering my own question, but for the sake of anyone else having the same issues. Here's how it works:
If you're putting a literal value in the field, just use the value
If you're using any other kind of assignment, do a lookup based on the value.
The code below demonstrates:
var fieldValue = FieldValue.StartsWith("{") ? ctx.AddContextDataToString(FieldValue, true) : FieldValue;
This extract the value from the workflow context. Hope this helps.